<template>
  <div class="commodity-admin">
    <!-- 查询区域 -->
    <el-card style="margin-bottom: 10px">
      <el-row :gutter="10">
        <el-col :span="6">
          <el-form-item label="商品名称">
            <el-input
              v-model="queryParams.commodityName"
              placeholder="请输入商品名称"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="商品简介">
            <el-input
              v-model="queryParams.commodityDescription"
              placeholder="请输入商品简介"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="分类ID">
            <el-input
              v-model="queryParams.commodityTypeId"
              placeholder="请输入分类ID"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="是否上架">
            <el-select
              v-model="queryParams.isListed"
              placeholder="请选择"
              clearable
            >
              <el-option label="未上架" :value="0" />
              <el-option label="已上架" :value="1" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item>
            <el-button @click="resetQuery">重置</el-button>
            <el-button type="primary" @click="getCommodityList">查询</el-button>
            <el-button type="primary" @click="showAddDialog" :icon="Promotion">
              添加商品
            </el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-card>

    <!-- 商品列表表格 -->
    <el-card>
      <el-table :data="commodityList" style="width: 100%" :loading="loading">
        <el-table-column prop="commodityName" label="商品名称" />
        <el-table-column
          prop="commodityDescription"
          label="商品简介"
          width="150px"
          show-overflow-tooltip
        />
        <el-table-column label="商品封面" prop="commodityAvatar" width="100px">
          <template #default="{ row }">
            <el-image :src="row.commodityAvatar" style="width: 64px" />
          </template>
        </el-table-column>
        <el-table-column
          prop="commodityTypeId"
          label="分类ID"
          show-overflow-tooltip
        />
        <el-table-column prop="commodityTypeName" label="分类名称" />
        <el-table-column prop="isListed" label="是否上架">
          <template #default="{ row }">
            <el-tag :type="row.isListed === 1 ? 'success' : 'danger'">
              {{ row.isListed === 1 ? "已上架" : "未上架" }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="price" label="价格" />
        <el-table-column
          prop="commodityInventory"
          label="商品库存"
          width="60px"
        />
        <el-table-column prop="favourNum" label="收藏数" width="50px" />
        <el-table-column prop="viewNum" label="浏览量" width="50px" />
        <el-table-column prop="updateTime" label="更新时间" />
        <el-table-column label="操作" width="260px">
          <template #default="{ row }">
            <el-button type="primary" @click="showEditDialog(row.id)">修改
            </el-button>
            <el-button type="success" size="medium" @click="showComments(row.id)">评论</el-button>
            <el-popconfirm
              title="你确定要删除该商品吗？"
              @confirm="deleteCommodity(row)"
              @cancel="cancelEvent">
              <template #reference>
                <el-button type="danger">删除</el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        style="margin-top: 20px"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :page-sizes="[5, 10, 15, 20]"
        :current-page="paginationConfig.current"
        :total="paginationConfig.total"
        :page-size="paginationConfig.pageSize"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>

    <!-- 修改商品的对话框 -->
    <el-dialog
      title="修改商品"
      v-model="editDialogVisible"
      width="50%"
      @close="resetEditField(editFormRef)"
    >
      <el-form :model="editForm" ref="editFormRef" label-width="100px">
        <el-form-item label="商品名称" prop="commodityName">
          <el-input v-model="editForm.commodityName" />
        </el-form-item>
        <el-form-item label="商品简介" prop="commodityDescription">
          <el-input type="textarea" v-model="editForm.commodityDescription" />
        </el-form-item>
        <el-form-item label="商品封面" prop="commodityAvatar">
          <el-upload
              :show-file-list="false"
              :before-upload="beforeUpload"
              :auto-upload="false"
              :on-change="handleFileChange"
          >
            <img
                v-if="editForm.commodityAvatar"
                :src="editForm.commodityAvatar"
                class="avatar"
                style="height: 128px; width: 128px; border-radius: 50%"
            />
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
            <template #tip>
              <div class="el-upload__tip">
                点击头像上传，支持 JPG/PNG 格式，大小不超过 2MB
              </div>
            </template>
          </el-upload>
        </el-form-item>

        <!-- 商品视频上传 -->
        <el-form-item label="商品视频" prop="commodityAvatar">
          <el-upload
              :show-file-list="false"
              :before-upload="beforeUpload"
              :auto-upload="false"
              :on-change="handleFileChange"
          >
            <p v-if="editForm.commodityVideo" style="color: #0077aa;font-size: 13px;">
              点击修改:{{editForm.commodityVideo}}
            </p>
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
            <template #tip>
              <div class="el-upload__tip">点击上传商品视频，大小不超过 2MB</div>
            </template>
          </el-upload>
        </el-form-item>
        <el-form-item label="商品分类" prop="commodityTypeId">
          <!-- 父类选择 -->
          <el-select
              style="width: 170px"
              v-model="editForm.parentTypeId"
              placeholder="请选择父类"
              @change="loadChildTypes"
          >
            <el-option
                v-for="type in parentTypeList"
                :key="type.id"
                :label="type.typeName"
                :value="type.id"
            />
          </el-select>

          <!-- 子类选择 -->
          <el-select
              v-model="editForm.childTypeId"
              placeholder="请选择子类"
              style="margin-left: 10px;width: 180px"
          >
            <el-option
                v-for="type in childTypeList"
                :key="type.id"
                :label="type.typeName"
                :value="type.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="是否上架" prop="isListed">
          <el-select v-model="editForm.isListed" placeholder="请选择">
            <el-option label="未上架" :value="0" />
            <el-option label="已上架" :value="1" />
          </el-select>
        </el-form-item>
        <el-form-item label="价格" prop="price">
          <el-input v-model="editForm.price" />
        </el-form-item>
        <el-form-item label="商品库存" prop="commodityInventory">
          <el-input-number
            v-model="editForm.commodityInventory"
            :min="0"
            :step="1"
            controls-position="right"
          />
        </el-form-item>
      </el-form>
      <span class="dialog-footer">
        <slot name="footer">
          <el-button @click="resetEditField(editFormRef)">取消</el-button>
          <el-button type="primary" @click="editCommodity">确定</el-button>
        </slot>
      </span>
    </el-dialog>

    <!-- 添加商品的对话框 -->
    <el-dialog
        title="添加商品"
        v-model="addDialogVisible"
        width="630px"
        @close="addDialogClosed"
    >
      <el-form :model="addForm" ref="addFormRef" label-width="100px">
        <!-- 商品名称 -->
        <el-form-item label="商品名称" prop="commodityName" style="width: 400px">
          <el-input v-model="addForm.commodityName" placeholder="请输入商品名称" />
        </el-form-item>
        <!-- 商品简介 -->
        <el-form-item label="商品简介" prop="commodityDescription" style="width: 400px">
          <el-input
              type="textarea"
              v-model="addForm.commodityDescription"
              placeholder="请输入商品简介"
          />
        </el-form-item>

        <!-- 商品封面 -->
        <el-form-item label="商品封面" prop="commodityAvatar">
          <el-upload
              :show-file-list="false"
              :before-upload="beforeUpload"
              :auto-upload="false"
              :on-change="handleFileChange"
          >
            <img
                v-if="addForm.commodityAvatar"
                :src="addForm.commodityAvatar"
                class="avatar"
                style="height: 128px; width: 128px; border-radius: 50%"
             alt=""/>
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
            <template #tip>
              <div class="el-upload__tip">点击上传，支持 JPG/PNG 格式，大小不超过 2MB</div>
            </template>
          </el-upload>
        </el-form-item>
        <!-- 商品视频上传 -->
        <el-form-item label="商品视频" prop="commodityAvatar">
          <el-upload
              :show-file-list="false"
              :before-upload="beforeUpload"
              :auto-upload="false"
              :on-change="handleFileChange"
          >
            <p v-if="addForm.commodityVideo" style="color: #0077aa;font-size: 13px;">
              上传成功:{{addForm.commodityVideo}}
            </p>
            <el-icon v-else class="avatar-uploader-icon">
              <Plus />
            </el-icon>
            <template #tip>
              <div class="el-upload__tip">点击上传商品视频，大小不超过 2MB</div>
            </template>
          </el-upload>
        </el-form-item>

        <!-- 商品分类 -->
        <el-form-item label="商品分类" prop="commodityTypeId">
          <!-- 父类选择 -->
          <el-select
              style="width: 170px"
              v-model="addForm.parentTypeId"
              placeholder="请选择父类"
              @change="loadChildTypes"
          >
            <el-option
                v-for="type in parentTypeList"
                :key="type.id"
                :label="type.typeName"
                :value="type.id"
            />
          </el-select>

          <!-- 子类选择 -->
          <el-select
              v-model="addForm.childTypeId"
              placeholder="请选择子类"
              style="margin-left: 10px;width: 180px"
          >
            <el-option
                v-for="type in childTypeList"
                :key="type.id"
                :label="type.typeName"
                :value="type.id"
            />
          </el-select>
        </el-form-item>

        <!-- 是否上架 -->
        <el-form-item label="是否上架" prop="isListed" style="width: 400px">
          <el-select v-model="addForm.isListed" placeholder="请选择">
            <el-option label="未上架" :value="0" />
            <el-option label="已上架" :value="1" />
          </el-select>
        </el-form-item>

        <!-- 价格 -->
        <el-form-item label="价格" prop="price" style="width: 400px">
          <el-input v-model="addForm.price" placeholder="请输入价格" />
        </el-form-item>

        <!-- 商品库存 -->
        <el-form-item label="商品库存" prop="commodityInventory">
          <el-input-number
              v-model="addForm.commodityInventory"
              :min="1"
              :step="1"
              controls-position="right"
          />
        </el-form-item>
      </el-form>

      <!-- 操作按钮 -->
      <span class="dialog-footer" style="margin-left: 100px">
      <slot name="footer">
        <el-button @click="addDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="addCommodity">添加</el-button>
      </slot>
    </span>
    </el-dialog>


    <!--评论对话框--->
    <el-dialog
        title="商品评论区域"
        v-model="commentDialogVisible"
        width="930px"
        @close=" commentDialogVisible=false"
    >
      <MerchantCommodityComment
          :is-bought="false"
          :merchant-commodity-id="currentCommodityId"
      >
      </MerchantCommodityComment>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from "vue";
import {
  ElButton,
  ElDialog,
  ElForm,
  ElFormItem,
  ElInput,
  ElMessage,
  ElTag,
  ElSelect,
  ElOption,
  FormInstance,
  ElImage,
  ElTableColumn
} from "element-plus";
import { Promotion } from "@element-plus/icons-vue";
import {
  addCommodityUsingPost,
  deleteCommodityUsingPost,
  getCommodityVoByIdUsingGet,
  updateCommodityUsingPost
} from "@/api/commodityController";

import request from "@/utils/request";
import MerchantCommodityComment from "../../../components/MerchantCommodityComment/index.vue"
// 查询参数
const queryParams = ref({
  commodityName: "",
  commodityDescription: "",
  commodityTypeId: "",
  isListed: undefined, //表示上架
  viewNum:"",
  price: undefined,
});

// 商品列表
const commodityList = ref([]);
const loading = ref<boolean>(false);

// 商品分类列表
const commodityTypeList = ref([]);

// 分页配置
const paginationConfig = ref({
  pageSize: 10,
  total: 0,
  current: 1
});

// 对话框状态
const editDialogVisible = ref(false);
const addDialogVisible = ref(false);

// 表单引用
const editFormRef = ref<FormInstance>();
const addFormRef = ref<FormInstance>();

// 编辑表单数据
const editForm = ref({
  id: 0,
  commodityName: "",
  commodityDescription: "",
  commodityTypeId: "",
  isListed: 0,
  price: 0,
  commodityAvatar: "",
  commodityVideo:null, //商品视频
  commodityInventory: 1,
  parentTypeId: "",//父类id
  childTypeId: "" //子类id
});

// 添加表单数据
const addForm = ref({
  commodityName: "",  //*
  commodityDescription: "", //*
  commodityTypeId: "",//*
  isListed: 0,//*
  price: 0,//*
  commodityAvatar: "",//*
  commodityVideo:null, //商品视频
  commodityInventory: 1,//*
  parentTypeId: "",//父类id
  childTypeId: "" //子类id
});

// 商家获取商品列表 只能查看自己的
const getCommodityList = async () => {
  loading.value = true;
  try {
    const res = await request.post("/api/commodity/my/list/page/vo",{
      ...queryParams.value,
      current: paginationConfig.value.current,
      pageSize: paginationConfig.value.pageSize
    });
    if (res.code === 200) {
      commodityList.value = res.data.records;
      paginationConfig.value.total = parseInt(res.data.total);
    } else {
      ElMessage.error("获取商品列表失败");
    }
  } catch (error) {
    ElMessage.error("获取商品列表失败");
  } finally {
    loading.value = false;
  }
};

// 重置查询条件
const resetQuery = () => {
  queryParams.value = {
    commodityName: "",
    commodityDescription: "",
    degree: "",
    commodityTypeId: "",
    isListed: ""
  };
  getCommodityList();
};

const isEdit= ref(false);
// 显示修改对话框
const showEditDialog = async (id: number) => {
  isEdit.value = true;
  loading.value = true;
  try {
    const res = await getCommodityVoByIdUsingGet({ id });
    if (res.code === 200) {
      // 过滤不需要的字段
      const filteredData = {};
      for (const [key, value] of Object.entries(res.data)) {
        if (!["createTime", "updateTime"].includes(key)) {
          filteredData[key] = value;
        }
      }
      editForm.value = filteredData;
      editDialogVisible.value = true;
    } else {
      ElMessage.error("获取商品信息失败");
    }
  } catch (error) {
    ElMessage.error("获取商品信息失败");
  } finally {
    loading.value = false;
  }
};

// 修改商品
const editCommodity = async () => {
  try {
    editForm.value.commodityTypeId = editForm.value.childTypeId
    const res = await updateCommodityUsingPost(editForm.value);
    if (res.code === 200) {
      ElMessage.success("修改商品成功");
      editDialogVisible.value = false;
      await getCommodityList();
    } else {
      ElMessage.error("修改商品失败");
    }
  } catch (error) {
    ElMessage.error("修改商品失败");
  }
};

// 添加商品
const addCommodity = async () => {
  addForm.value.commodityTypeId = addForm.value.childTypeId
  console.log("addForm is ",addForm.value)
  try {
    const res = await addCommodityUsingPost(addForm.value);
    if (res.code === 200) {
      ElMessage.success("添加商品成功");
      addDialogVisible.value = false;
      await getCommodityList();
    } else {
      ElMessage.error("添加商品失败");
    }
  } catch (error) {
    ElMessage.error("添加商品失败");
  }
};

// 删除商品
const deleteCommodity = async (row) => {
  try {
    const res = await deleteCommodityUsingPost({ id: row.id });
    if (res.code === 200) {
      ElMessage.success("删除商品成功");
      await getCommodityList();
    } else {
      ElMessage.error("删除商品失败");
    }
  } catch (error) {
    ElMessage.error("删除商品失败");
  }
};

// 关闭添加对话框
const addDialogClosed = () => {
  addForm.value = {
    commodityName: "",
    commodityDescription: "",
    degree: "",
    commodityTypeId: "",
    isListed: 0,
    price: 0,
    commodityAvatar: "",
    commodityInventory: 1
  };
};

// 关闭修改对话框
const resetEditField = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  editDialogVisible.value = false;
  formEl.resetFields();
};

// 分页处理
const handleSizeChange = (size: number) => {
  paginationConfig.value.pageSize = size;
  getCommodityList();
};

const handleCurrentChange = (page: number) => {
  paginationConfig.value.current = page;
  getCommodityList();
};

// 取消删除
const cancelEvent = () => {
  ElMessage.success("取消删除成功");
};

// 显示添加对话框
const showAddDialog = () => {
  isEdit.value = false
  addDialogVisible.value = true;
};

// 初始化加载商品列表和商品分类列表
onMounted(() => {
  getCommodityList();
  loadParentTypes()
});

//
// 上传前验证
const beforeUpload = (file: File) => {

  //大小限制  只能为jpg   png  mp4
  if (file.size > 1024 * 1024 * 10) {
    ElMessage.error("文件大小不能超过10M");
    return false
  }
  return (file.type === 'image/jpeg' || file.type === 'image/png' || file.type === 'video/mp4')
}

// 文件选择变化时触发
const handleFileChange = (file) => {
  const fileType = file.raw.type
   handleUpload(file.raw, fileType)
}

// 通用上传函数
const handleUpload = async (file,fileType) => {
  try {

    const form = new FormData()
    form.append('file', file)
    // 调用自定义API
    const response = await request.post('/api/file/upload', form, {
      headers: {
        'Content-Type': 'multipart/form-data'
      },
    })

    console.log("上传 res is ", response)
    console.log("isEdit isEdit is ",isEdit.value)
    // 上传成功处理
    //@ts-ignore
    if (response.code === 200) {
      if (isEdit.value) {
        console.log("isEdit is true")
        if (fileType === "image/jpeg" || fileType === "'image/png'") {
          console.log("type is avatar")
          editForm.value.commodityAvatar = response.data
        } else if (fileType === "video/mp4") {
          console.log("type is video")
          editForm.value.commodityVideo = response.data
        }
        else{
          console.log("add type is null")
        }
      }
      //新增
      else {
        if (fileType === "image/jpeg" || fileType === "'image/png'") {
          addForm.value.commodityAvatar = response.data
        }
        else if (fileType === "video/mp4") {
          addForm.value.commodityVideo = response.data
        }
        else{
          console.log(" add type is null")
        }
      }
      ElMessage.success('上传成功')
    } else {
      ElMessage.error(response.data.message || '上传失败')
    }
  } catch (error) {
    console.error('上传错误:', error)
    ElMessage.error('上传失败: ' + (error.message || '网络错误'))
  } finally {
    // isEdit.value = false
  }
};

//父子类别
// 分类相关数据
const selectedParentType = ref<number | null>(null)
const parentTypeList = ref<any[]>([])
const childTypeList = ref<any[]>([])
const loadingChildTypes = ref(false)
// 加载父分类
const loadParentTypes = async () => {
  try {
    const res = await request.get("/api/commodityType/get/parent");
    // @ts-ignore
    if (res.code === 200) {
      parentTypeList.value = res.data
    } else {
      // @ts-ignore
      ElMessage.error(res.message || '获取父分类失败')
    }
  } catch (error) {
    ElMessage.error('获取父分类失败')
  }
}

// 父分类变化时加载子分类
const loadChildTypes = async (parentId: number) => {
  if (!parentId) {
    childTypeList.value = []
    //@ts-ignore
    addForm.value.commodityTypeId = null
    return
  }

  loadingChildTypes.value = true
  try {
    const res = await request.get("/api/commodityType/get/children",{
      params: {
        parentId
      }
    })
    //@ts-ignore
    if (res.code === 200) {
      childTypeList.value = res.data
      // 自动选择第一个子类（可选）
      if (res.data.length === 1) {
        addForm.value.commodityTypeId = res.data[0].id
      }
    } else {
      ElMessage.error(res.message || '获取子分类失败')
    }
  } catch (error) {
    ElMessage.error('获取子分类失败')
  } finally {
    loadingChildTypes.value = false
  }
}
const commentDialogVisible = ref(false)
const currentCommodityId=ref()
///评论内容
const showComments = (id) => {
  commentDialogVisible.value = true
  ElMessage.success("商品id：" + id)
  currentCommodityId.value=id
}





</script>

<style scoped>
.commodity-admin {
  padding: 20px;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
}

</style>
